<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Traits\JsonResponse;
use App\Http\Requests\Admin\WechatImageStore;
use App\Http\Requests\Admin\WechatNewsStore;
use App\Http\Resources\Admin\WechatMaterialResource;
use App\Models\Material;
use App\Services\WechatMaterialService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Overtrue\LaravelWeChat\Facade as EasyWechat;
use App\Http\Controllers\Controller;

class WechatMaterialsController extends Controller
{
    /**
     * 图文素材列表
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function newsIndex(Request $request)
    {
        $pageSize = $request->input('page_size') ?: 15;
        $list = Material::query()->where('type', Material::TYPE_NEWS)
            ->where('index', 0)
            ->select(['id', 'media_id', 'index', 'thumb_url', 'title', 'digest',])
            ->paginate($pageSize);

        return WechatMaterialResource::collection($list)->additional(JsonResponse::$resourceAdditionalMeta);
    }

    /**
     * 图片素材列表
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function imagesIndex(Request $request)
    {
        $pageSize = $request->input('page_size') ?: 15;
        $list = Material::query()->where('type', Material::TYPE_IMAGE)
            ->select(['id', 'media_id', 'name', 'url'])
            ->paginate($pageSize);

        return WechatMaterialResource::collection($list)->additional(JsonResponse::$resourceAdditionalMeta);
    }

    /**
     * 同步图文素材
     * @param WechatMaterialService $materialService
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function syncNews(WechatMaterialService $materialService)
    {
        $app = EasyWechat::officialAccount();
        // 获取图文素材总数
        $stats = $app->material->stats();
        if ($stats['news_count']) {
            for ($i = 0; $i < $stats['news_count']; $i = $i + 20) {
                // 获取图文素材列表
                $list = $app->material->list(Material::TYPE_NEWS, $i);
                // 同步图文素材
                $materialService->syncNews($list['item']);
            }
        }
        return $this->message('同步成功');
    }

    /**
     * 同步图片素材
     * @param WechatMaterialService $materialService
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function syncImages(WechatMaterialService $materialService)
    {
        $app = EasyWechat::officialAccount();
        $stats = $app->material->stats();
        if ($stats['image_count']) {
            for ($i = 0; $i < 20; $i = $i + 20) {
                $list = $app->material->list(Material::TYPE_IMAGE, $i);
                // 同步图片素材
                $materialService->syncImages($list['item']);
            }
        }
        return $this->message('同步成功');
    }

    /**
     * 上传图文消息内的图片
     * @param Request $request
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function uploadNewsImage(Request $request)
    {
        $app = EasyWechat::officialAccount();
        $path = $request->file('img')->store('news_images');
        $path = storage_path('app/' . $path);
        $result = $app->material->uploadArticleImage($path);
        // 删除本地图片
        unset($path);

        return $this->success($result);
    }

    /**
     * 上传图文素材
     * @param WechatNewsStore $request
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function storeNews(WechatNewsStore $request)
    {
        $app = EasyWechat::officialAccount();
        $articles = collect($request->input('articles'))->map(function ($article) {
            $article['content'] = urldecode($article['content']);
            return $article;
        })->all();
        $result = $app->material->uploadArticle($articles);
        if (isset($result['errcode'])) {
            return $this->failed($result['errmsg'], $result['errcode']);
        }

        DB::transaction(function () use ($result, $articles) {
            foreach ($articles as $index => $article) {
                $article['type'] = Material::TYPE_NEWS;
                $article['index'] = $index;
                $article['media_id'] = $result['media_id'];
                Material::query()->create($article);
            }
        });
        return $this->message('新增成功');
    }

    /**
     * 上传图片素材
     * @param WechatImageStore $request
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function storeImage(WechatImageStore $request)
    {
        $app = EasyWechat::officialAccount();
        $filename = $request->input('name') . '.' . $request->file('img')->extension();
        $path = $request->file('img')->storeAs('images', $filename);
        $path = storage_path('app/' . $path);
        $result = $app->material->uploadImage($path);
        // 删除本地图片
        unlink($path);

        if (isset($result['errcode'])) {
            return $this->failed($result['errmsg'], $result['errcode']);
        }

        // 保存素材资源至数据库
        $result['type'] = Material::TYPE_IMAGE;
        Material::query()->create($result);
        return $this->message('新增成功');
    }
}
